import { observable, action } from 'mobx'
import lrz from 'lrz'
import * as api from 'lib/constants/api'
import { post } from 'lib/net'
import Toast from 'components/toast'
// import Load from 'components/load'

// class AddressModel {
//   constructor (data) {
//     if (data) {
//     }
//   }
// }

// 添加意见内容
var AttachList = []
export default class AdviseVM {
  constructor (props) {
    this.props = props
    this.PageInitialization()
  }

  @observable test = ''

  // 添加意见内容
  @observable Content = ''

  // 增加图片
  @action handleAddImageClick = e => {
    let file = e.target.files[0]
    if (file && file.size <= 0) return
    this.compressImage(file)
    e.target.value = ''
  }

  // 压缩图片
  @action compressImage = file => {
    Toast.loading(1, '正在压缩')
    lrz(file, { width: 800 })
      .then(rst => {
        this.updateImage({ Base64: rst.base64, ImageName: file.name })
      }).catch(() => {
        this.loading = false
        Toast.fail('压缩失败')
      })
  }

  // 上传图片
  @action updateImage = async params => {
    Toast.loading(1, '正在上传')
    let res = await post(api.UPLOADIMA64, params)
    if (res.Success === true) {
      AttachList.push({AttachType: 0, AttachUrl: res.Value})
      let container = document.getElementById('upload-img-box')
      let message = document.getElementById('upload-img')
      let para = document.createElement('img')
      para.setAttribute('src', api.WZ_IMAGE_PATH + res.Value)
      para.setAttribute('class', 'user-upload')
      container.insertBefore(para, message)
      let lengthImg = container.getElementsByClassName('user-upload').length
      if (lengthImg === 3) {
        container.removeChild(container.childNodes[3])
      }
      Toast.success('上传成功')
    } else {
      Toast.fail('上传失败')
    }
  }

  // 获取页面意见
  @action onChange = (v) => {
    this.Content = v
  }

  // 去除字符串中的空格
  @action myTrim = (str, global) => {
    let result
    result = str.toString().replace(/(^\s+)|(\s+$)/g, '')
    if (global.toLowerCase() === 'g') {
      result = result.replace(/\s/g, '')
    }
    return result
  }
  // 提交意见
  @action handleSubmit = async () => {
    let params = {
      UserId: window.localStorage.getItem('UserId'),
      Content: this.Content,
      AttachList: AttachList
    }
    if (this.myTrim(this.Content, 'g') === '') {
      Toast.fail('请留下您的宝贵意见')
    } else {
      let response = await post(api.ADDFEEDBACK, params)
      if (response.Success) {
        Toast.success('意见反馈成功')
        setTimeout(() => {
          this.props.history.push('/userCenter')
        }, 1000)
      } else {
        Toast.fail(response.Message)
      }
    }
  }

  @action PageInitialization = async () => {
  }
}
